<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'models/m_object.php';

/**
 * Модель torrent файла видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class M_Video_Torrent extends M_Object {
   
   /**
    * Название таблицы
    *
    * @access protected
    * @var string
    */
   var $_table = 'video_torrents';
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return M_Video_Torrent
    */
   function M_Video_Torrent() {
      parent::M_Object();
      $this->load->helper('torrent');
   } // end M_Video_Torrent
   
   /**
    * Удаление записи
    *
    * @access protected
    * @return boolean
    */
   function _delete() {
      if (parent::_delete()) {
         // Обновляем видео
         $this->_update_video();
         return true;
      }
      return false;
   } // end _delete
   
   /**
    * Вставка записи
    *
    * @access protected
    * @return boolean
    */
   function _insert() {
      if (parent::_insert()) {
         $this->_update_video();
         return true;
      }
      return false;
   } // end _insert
   
   /**
    * Изменение записи
    *
    * @access protected
    * @return boolean
    */
   function _update() {
      if (parent::_update()) {
         $this->_update_video();
         return true;
      }
      return false;
   } // end _update
   
   /**
    * Download torrent
    */
   function download() {
      $sql = "
         UPDATE
            " . $this->db->dbprefix('video_torrents') . "
         SET
            num_downloaded = num_downloaded + 1
         WHERE
            id_torrent = " . $this->db->escape($this->get_id('id_torrent')) . "
      ";
      if (false !== ($this->db->query($sql))) {
         $this->_update_video();
         return true;
      }
      return false;
   }
   
   /**
    * Get torrent info
    */
   function get_stats() {
      $stats = array();
      /*
      $key = $this->get_id('id_torrent');
      $this->load->library('cache');
      if (null === ($stats = $this->cache->get($key, 'torrents-info'))) {
         $stats = torrent_stats($this->get('torrent'));
         if (!empty($stats)) {
            $this->cache->save($key, $stats, 'torrents-info', 3600);
         }
      }
      */
      return $stats;
   }
   
   /**
    * Get torrent content
    */
   function get_content() {
      $torrent = $this->get('torrent');
      $content = null;
      if (preg_match('~^https?://~', $torrent)) {
          $key = $torrent;
          $this->load->library('cache');
          if (null === ($content = $this->cache->get($key, 'torrents'))) {
             $this->load->helper('http');
             $headers = array(
                'Referer: ' . $this->get('link')
             );
             $proxy = array();
             if (false !== strpos($this->get('link'), 'tfile.ru')) {
                $proxy = get_random_proxy();
             }
             $content = get_content($torrent, $headers, 0, '', array(), $proxy);
             // Декодируем исходный файл
             $data = torrent_decode($content);
             if (!empty($data)) {
                $this->cache->save($key, $content, 'torrents', 86400);
             } else {
                $content = null;
             }
          }
      } elseif (file_exists(BASEPATH . '../' . $torrent)) {
          $content = file_get_contents(BASEPATH . '../' . $torrent);
      }
      return $content;
   }
   
   /**
    * Метод обновления поля num_torrents у видео
    *
    */
   function _update_video() {
      $sql = "
         UPDATE
            " . $this->db->dbprefix('videos') . "
         SET
            num_torrents = (
               SELECT
                  COUNT(*)
               FROM
                  " . $this->db->dbprefix('video_torrents') . " vt
               WHERE
                  vt.id_video = " . $this->db->dbprefix('videos') . ".id_video
            ),
            num_downloaded = (
               SELECT
                  SUM(num_downloaded)
               FROM
                  " . $this->db->dbprefix('video_torrents') . " vt
               WHERE
                  vt.id_video = " . $this->db->dbprefix('videos') . ".id_video
            )
         WHERE
            id_video = " . $this->db->escape($this->get('id_video')) . "
      ";
      $this->db->query($sql);
   }
   
}
